# coding=utf-8
# 当前目录搭建web服务器
# python -m SimpleHTTPServer 8000
# .pyw 后台进程运行
# nohup python -u server.py> nohup.out 2>&1 &

# import os
# import sys
# 添加工作目录到path
# sys.path.append(os.path.sep.join(os.getcwdu().split(os.path.sep)[0:-3]))
import urllib
from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler
import json
from httpresult import MyHttpResult
from aes_util import AESUtil
import time

# 自定义处理程序，用于处理HTTP请求


class MyHTTPHandler(BaseHTTPRequestHandler):
    # 处理GET请求

    def do_GET(self):
        query = urllib.splitquery(self.path)
        path=query[0]

        print "-"*100
        print time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        
        # 解析请求参数
        queryStr=query[1]
        queryData={}
        if queryStr!=None:
            for key_value in queryStr.split("&"):
                strs=key_value.split("=")
                queryData[strs[0]]=strs[1]
        
        print queryData
        headers=self.headers
        
        #客户端ip
        if headers.has_key("X-Forwarded-For"):
            requestIp=headers["X-Forwarded-For"].split(",")[0]
        elif headers.has_key("X-Real-IP"):
            requestIp=headers["X-Real-IP"]
        else:
            requestIp=self.client_address[0]
        
        httpResult=MyHttpResult()
        httpResult.put("requestIp", requestIp)

        if path=="/ssh-upload":
            configFile = open("config.json",mode='r')
            configJson=json.load(configFile)
            print requestIp
            
            _server=""
            _user=""
            if queryData.has_key("server"):
                _server=queryData["server"]
                
            if queryData.has_key("user"):
                _user=queryData["user"]
            print _server,_user
            if configJson.has_key("server") and configJson["server"].has_key(_server) and configJson.has_key("user") and configJson["user"].has_key(_user):
                #账户配置
                userConf=configJson["user"][_user]
                #玩家当前可上传服务器
                userServer=""
                if userConf.has_key("server"):
                    userServer=userConf["server"]
                    print 'userServer',userServer
                if userServer==_server:
                    #服务器配置
                    serverConf=configJson["server"][_server]
                    #是否检查IP
                    _checkIp=True
                    if userConf.has_key("checkIp"):
                        _checkIp=userConf["checkIp"]
                        
                    _ips=["27.115.11.62","127.0.0.1"]   #默认IP
                    if userConf.has_key("ips"):
                        _ips+=userConf["ips"]
                    print _ips
                    #判断ip是否允许访问
                    if requestIp in _ips or requestIp.startswith("192.168.") or _checkIp==False:
                        _mac=""
                        print "userConf",userConf
                        if userConf.has_key("mac") and userConf.has_key("uploadDir"):
                            _mac=userConf["mac"]
                            _uploadDir=userConf["uploadDir"]
                            print _mac,_uploadDir
                            if len(_mac)>0 and len(_uploadDir)>0:
                                if serverConf.has_key("ip") and serverConf.has_key("user") and serverConf.has_key("pwd"):
                                    _serverIp=serverConf["ip"]
                                    _serverUser=serverConf["user"]
                                    _serverPwd=serverConf["pwd"]
                                    print _serverIp,_serverUser,_serverPwd
                                    if len(_serverIp)>0 and len(_serverUser)>0 and len(_serverPwd)>0:
                                        aesUtil=AESUtil(_mac)
                                        httpResult.put("server", aesUtil.encrypt(json.dumps({
                                                "ip":_serverIp
                                                ,"user":_serverUser
                                                ,"pwd":_serverPwd
                                                ,"dir":_uploadDir
                                            })))
                                        httpResult.isSuccess()
                    else:
                        httpResult.setCode(2,"unauthorized!!!")
                else:
                    httpResult.setCode(3,"unauthorized!!!")
        print httpResult.getResult()
        self.protocal_version = 'HTTP/1.1'  #设置协议版本  
        self.send_response(200) #设置响应状态码  
        self.end_headers()
        self.wfile.write((json.dumps(httpResult.getResult(),indent=4)))
        #启动服务函数  
def start_server(port):
        http_server = HTTPServer(('', int(port)), MyHTTPHandler)
        http_server.serve_forever() #设置一直监听并接收请求  

# os.chdir('static')  # 改变工作目录到 static 目录
start_server(8000)  # 启动服务，监听8000端口
